package com.liushao.controller;


import com.liushao.entity.LendReturn;
import com.liushao.hfb.RequestHelper;
import com.liushao.result.Result;
import com.liushao.service.LendReturnService;
import com.liushao.util.JwtUtils;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.swing.*;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 还款记录表 前端控制器
 * </p>
 *
 * @author chen
 * @since 2025-01-03
 */
@RestController
@RequestMapping("/api/core/lendReturn")
public class LendReturnController {

    @Autowired
    private LendReturnService lendReturnService;

    //  '/api/core/lendReturn/list/' + lendId
    @GetMapping("/list/{lendId}")
    public Result list(
            @ApiParam(value = "标的id ",required = true)
            @PathVariable Long lendId
    ){
        List<LendReturn> lendReturnList = lendReturnService.selectLendById(lendId);

        return Result.ok().data("list",lendReturnList);
    }


    //.$post('/api/core/lendReturn/auth/commitReturn/' + lendReturnId)
    @ApiOperation("用户还款")
    @PostMapping("/auth/commitReturn/{lendReturnId}")
    public Result commitReturn(
            @ApiParam(value = "还款计划id",required = true)
            @PathVariable Long lendReturnId, HttpServletRequest request
            ){
        
        String token = null;
        Cookie[] cookies = request.getCookies();
        for (Cookie cookie : cookies){
            if(cookie.getName().equals("token")){
                token = cookie.getValue();
                break;
            }
        }
        Long userId = JwtUtils.getUserId(token);

        String formStr=lendReturnService.commitReturn(lendReturnId,userId);


        return  Result.ok().data("formStr",formStr);

    }

    // http://localhost/api/core/lendReturn/notifyUrl 处理回调

    @PostMapping("/notifyUrl")
    public String notifyss(HttpServletRequest request){
        Map<String, Object> objectMap = RequestHelper.switchMap(request.getParameterMap());

        if(RequestHelper.isSignEquals(objectMap)){
            if("0001".equals(objectMap.get("resultCode"))){
                lendReturnService.notifyss(objectMap);
            }else{
                return  "fail";
            }
        }else{
            System.out.println("回调签名存在问题.....");
            return  "fail";
        }

        return  "success";
    }




}

